package com.example.texted;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.texted.eventlistenerdemo.PercentEvent;
import com.example.texted.eventlistenerdemo.PercentListener;
import com.example.texted.eventlistenerdemo.testListenerExecuter;
import com.example.texted.templatemethod.MyKey;
import com.jcraft.jsch.JSchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.*;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.util.*;
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) throws IOException, JSchException {
        SpringApplication.run(DemoApplication.class, args);

        Properties properties = new Properties();
        properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("application-dev.properties"));
        String singKey = properties.getProperty("config.singKey");
        System.out.println(singKey);


//        String pid;
//        JschCmd.getInstance().init();
//        pid = JschCmd.getInstance().doCmd("ps aux | grep bootstrap.jar | grep -v grep | awk '{print $2}'");
//        if (StringUtils.isNotBlank(pid)) {
//            System.out.println("11111111111``" + pid);
//        }
//        System.out.println("222222222222``" + pid);


//        File file = new File(getPath());
//        String oldFilePath = file.getPath().replace("file:\\","").replace("file:","");
//        String newFilePath =oldFilePath+"Copy";
//        System.out.println(oldFilePath);
//        System.out.println(newFilePath);
//        System.out.println();
//        List<String> fileNames = new ArrayList<>();
//        findFileList(new File(oldFilePath),fileNames);
//        System.out.println(fileNames.size());
//        File newPath;
//        int count=0;
//        for (String fileName :  fileNames) {
//            String replace = fileName.replace(oldFilePath,newFilePath);
//            newPath = new File(new File(replace).getParent());
//            if (newPath.mkdirs()) {
//                System.out.println("创建目录 "+ newPath.getPath());
//            }
//            if (newPath.exists()) {
//                try {
//                    copyNio(fileName,replace);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                System.out.println("原文件"+fileName);
//                System.out.println("复制文件"+replace);
//                count++;
//            }
//
//        }
//        System.out.println("文件数"+count);

//        System.out.println("IP："+getIpAddress());
//        String linuxCmd ="java -jar /root/demo.jar";
//        String ip="172.16.199.148";
//        if (!execSSH(ip,linuxCmd)) {
//            System.exit(0);
//        }
//        System.out.println("ok");
//从配置文件中读取 目标服务器ip、端口、用户名、私钥路径
//        String ftpHost = prop.getProperty("downloadHost");
//        String port = prop.getProperty("downloadftpPort");
//        String ftpUserName = prop.getProperty("downloadUserName");
//        String priKeyBasePath = prop.getProperty("priBaseKeyPath");
//
//        String priKeyBasePath = "/root/.ssh/id_dsa";
////建立JSch对象
//        JSch jsch = new JSch();
//        Session session = null;
//        ChannelExec channelExec = null;
//        BufferedReader in = null;
//        try{
//            //添加私钥
//            jsch.addIdentity(priKeyBasePath);
//            session=jsch.getSession(ip);
//            //SSH 公钥检查机制 no、ask、yes
//            session.setConfig("StrictHostKeyChecking", "no");
//            session.connect();
//
//            channelExec  = (ChannelExec) session.openChannel("exec");
//            in = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
//            channelExec.setCommand("mkdir /root/test");
//            channelExec.setErrStream(System.err);
//            channelExec.connect();
//            while (in.ready()) {
//                String s = in.readLine();
//                System.out.println(s);
//            }
//        }catch (JSchException | IOException e) {
//            e.printStackTrace();
//        }finally {
//            if (channelExec != null) {
//                channelExec.disconnect();
//            }
//            if (session != null) {
//                session.disconnect();
//            }
//            if (in != null) {
//                try {
//                    in.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }


//        try {
//            JschCmd.getInstance().init();
//        } catch (JSchException | IOException e) {
//            e.printStackTrace();
//        }
//        String cmd = "sh /mnt/bin/DataToCSV.sh";
//        try {
//            String cmd1 = JschCmd.getInstance().doCmd(cmd);
//            System.out.println(cmd1);
//        } catch (JSchException | IOException e) {
//            e.printStackTrace();
//        }

//        List<String> coms = new ArrayList<>();
//        coms.add("mkdir /root/t1");
//        coms.add("mkdir /root/t2");
//        coms.add("mkdir /root/t3");
//        coms.add("mkdir /root/t4");
//        coms.add("mkdir /root/t5");
//        try {
//            JschCmd.getInstance().execCommandByShell(coms);
//        } catch (IOException | JSchException e) {
//            e.printStackTrace();
//        }
//        JschCmd.getInstance().close();

        Runtime.getRuntime().addShutdownHook(new JVMCloseHook());
    }

    public static boolean execSSH(String ip, String cmd) {
        try {
            Process exec = Runtime.getRuntime().exec("ssh " + ip);
            System.out.println("连接到" + ip);
            PrintStream out = new PrintStream(exec.getOutputStream());
            BufferedReader in = new BufferedReader(new InputStreamReader(exec.getInputStream()));
            BufferedReader err = new BufferedReader(new InputStreamReader(exec.getErrorStream()));
            out.println("mkdir /root/test" + "\n");
            String line;
//            while ((line = in.readLine()) != null) {
            while (in.ready()) {
                String s = in.readLine();
                System.out.println(s);
            }
            while (err.ready()) {
                String s = err.readLine();
                System.out.println(s);
            }
            out.println("exit" + "\n");
            try {
                System.out.println("等待执行…………");
                exec.waitFor();
                System.out.println("执行完成…………");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
//                out.close();
//                in.close();
//                exec.destroy();
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String executeLinuxCmd(String cmd) {
        System.out.println("执行命令[ " + cmd + "]");
        Runtime run = Runtime.getRuntime();
        try {
            Process process = run.exec(cmd);
            String line;
            BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder out = new StringBuilder();
            while ((line = stdoutReader.readLine()) != null) {
                out.append(line);
                out.append('\n');
            }
            try {
                System.out.println("等待执行…………");
                process.waitFor();
                System.out.println("执行完成…………");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                stdoutReader.close();
            }
            process.destroy();
            return out.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String getPath() {
        String path = DemoApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        if (System.getProperty("os.name").contains("dows")) {
//            path = path.substring(1);
        }
        if (path.contains("jar")) {
            path = path.substring(0, path.lastIndexOf("."));
            return path.substring(0, path.lastIndexOf("/"));
        }
        return path.replace("target/classes/", "");
    }

    /**
     * 读取目录下的所有文件
     *
     * @param dir       目录
     * @param fileNames 保存文件名的集合
     * @return
     */
    public static void findFileList(File dir, List<String> fileNames) {
        if (!dir.exists() || !dir.isDirectory()) {// 判断是否存在目录
            System.out.println("目录不存在");
            return;
        }
        String[] files = dir.list();// 读取目录下的所有目录文件信息
        if (files == null) {
            System.out.println("无文件");
            return;
        }
        Iterator<String> iterator = Arrays.stream(files).iterator();
        File file;
        while (iterator.hasNext()) {
            file = new File(dir, iterator.next());
            if (file.isFile()) {// 如果文件
                fileNames.add(dir + "/" + file.getName());// 添加文件全路径名
            } else {// 如果是目录
                findFileList(file, fileNames);// 回调自身继续查询
            }
        }
    }

    public static void copyFile(String oldFilePath, String newFilePath) {
        File oldFile = new File(oldFilePath);
        File newFile = new File(newFilePath);
        try {
            Files.copy(oldFile.toPath(), newFile.toPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void copyNio(String from, String to) throws IOException {

        try (FileChannel input = new FileInputStream(from).getChannel(); FileChannel output = new FileOutputStream(to).getChannel()) {
            input.transferTo(0, input.size(), output);
//            output.transferFrom(input, 0, input.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String getIpAddress() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                } else {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = addresses.nextElement();
                        if (ip != null && ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("IP地址获取失败" + e.toString());
        }
        return null;
    }

}
